package com.hmall.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.hmall.common.clients.UserClients;
import com.hmall.common.dto.ResultDTO;
import com.hmall.common.pojo.User;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.mapper.PayOrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.Password;
import com.hmall.order.service.ToPayService;
import com.hmall.order.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service("topayService")
public class TopPayServiceImpl extends ServiceImpl<OrderMapper, Order> implements ToPayService {

    @Autowired
    private UserClients userClients;


    @Autowired
    private PayOrderMapper payOrderMapper;

    @Override
    public ResultDTO pay(Long orderId, String password) {

        //根据id获取
        Order order = payOrderMapper.selectById(orderId);

        Long userId = ThreadLocalUtil.getUserId();

        ResultDTO resultDTO = new ResultDTO();

        if(order.getStatus()==1){
            User userById = userClients.getUserById(userId);

            Password password1 = JSONObject.parseObject(password, Password.class);

            String psw = DigestUtils.md5DigestAsHex(password1.getPassword().getBytes(StandardCharsets.UTF_8));

            System.out.println(userById.getPassword());

            if(psw.equals(userById.getPassword())){
                Long balance = userById.getBalance();
                Long totalFee = order.getTotalFee();
                Long status = balance-totalFee;

                userClients.update(status,userId);

                System.out.println("成功");
                resultDTO.setSuccess(true);
                resultDTO.setMsg("成功");
                resultDTO.setData(userById);

                payOrderMapper.updateById(order);
            }

        }
        resultDTO.setSuccess(false);
        resultDTO.setMsg("失败");
        return resultDTO;
    }



}
